package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.Approval;
import com.example.demo.entity.HeSuan;
import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import com.example.demo.enums.ApprovalNodeStatusEnum;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.ApprovalService;
import com.example.demo.service.RoleService;
import com.example.demo.vo.ApprovalVo;
import com.example.demo.vo.DataView;
import com.example.demo.vo.HeSuanVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Coding路人王
 * @date 2022/11/27 9:30
 */
@Controller
@RequestMapping("/approval")
public class ApprovalController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private ApprovalService approvalService;

    @Resource
    private UserMapper userMapper;


    @RequestMapping("/toApproval")
    public String toHeSuan(){
        return "approval/approval";
    }

    /**
     * 加载自己的审批
     * @param
     * @return
     */
    @RequestMapping("/loadMyApproval")
    @ResponseBody
    public DataView loadMyApproval(ApprovalVo approvalVo, HttpSession session){
        // 1.取到
        User user = (User) session.getAttribute("user");
        //获取用户uid
        Integer id = user.getId();
        approvalVo.setUid(id);
        //获取当前用户的rid，并获得对应的角色名称
        List<Integer> role = roleService.queryUserRoleById(id);
        Integer integer = role.get(0);
        Role byId = roleService.getById(integer);
        String roleName = byId.getName();
        if (StringUtils.isNotEmpty(user.getUsername())){
            String username = user.getUsername();
            Integer uid = user.getId();
            IPage<Approval> page = new Page<>(approvalVo.getPage(),approvalVo.getLimit());
            QueryWrapper<Approval> queryWrapper = new QueryWrapper();

            if (StringUtils.equals(roleName,"管理员") ){
                queryWrapper.le(StringUtils.isNotBlank(String.valueOf(uid)), "node_status", "6");
            }else if (StringUtils.equals(roleName,"学生")) {
                queryWrapper.le(StringUtils.isNotBlank(String.valueOf(uid)), "node_status", "6");
                queryWrapper.eq(StringUtils.isNotBlank(String.valueOf(uid)), "uid", uid);
            }else if (StringUtils.equals(roleName,"教师")){
                queryWrapper.le(StringUtils.isNotBlank(String.valueOf(uid)), "node_status", "6");
            }else if (StringUtils.equals(roleName,"院系")){
                queryWrapper.le(StringUtils.isNotBlank(String.valueOf(uid)), "node_status", "6");
            }else {
                queryWrapper.le(StringUtils.isNotBlank(String.valueOf(uid)), "node_status", "-1");
            }
//            queryWrapper.le(StringUtils.isNotBlank(String.valueOf(uid)), "node_status", "0");
//            queryWrapper.ge(StringUtils.isNotBlank(String.valueOf(uid)), "uid", uid);
            approvalService.page(page,queryWrapper);
            // 处理名字 需要优化 这里显示的都是自己的名字，别人提交的数据也显示自己的
            Map<Integer, String> collect = userMapper.selectList(new QueryWrapper<User>()).stream().collect(Collectors.toMap(User::getId, User::getUsername));
            List<Approval> records = page.getRecords();
            for (Approval a : records) {
                a.setUsername(collect.get(a.getUid()));
            }


            return new DataView(page.getTotal(),records);
        }
        return new DataView();
    }


    @RequestMapping("/addApproval")
    @ResponseBody
    public DataView addApproval(Approval approval,HttpSession session){
        approval.setCreateTime(new Date());
        // 未提交状态没有了   直接提交
        //获取当前用户uid
        User user = (User) session.getAttribute("user");
        Integer id = user.getId();
        approval.setUid(id);
        // 多种角色，最好每一个人有一种角色
        //获取当前用户的rid，并获得对应的角色名称
        List<Integer> role = roleService.queryUserRoleById(id);
        Integer integer = role.get(0);
        Role byId = roleService.getById(integer);
        String roleName = byId.getName();

        if (StringUtils.equals(roleName,"admin") || StringUtils.equals(roleName,"学生")){
            approval.setNodeStatus(ApprovalNodeStatusEnum.TEACHER_ING.getCode());
        }else if (StringUtils.equals(roleName,"教师")){
            approval.setNodeStatus(ApprovalNodeStatusEnum.COLLEGE_ING.getCode());
        }else if (StringUtils.equals(roleName,"院系")){
            approval.setNodeStatus(ApprovalNodeStatusEnum.COLLEGE_PASSED.getCode());
        }else {
            approval.setNodeStatus(ApprovalNodeStatusEnum.TEACHER_ING.getCode());
        }
        approvalService.save(approval);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("申请请假成功！");
        return dataView;
    }

    // /approval/success   RejectApproval




    @RequestMapping("/successApproval")
    @ResponseBody
    public DataView successApproval(Approval approval,HttpSession session){
        DataView dataView = new DataView();
        approval.setUpdateTime(new Date());
        // 1.首先判断是不是数据库中 审核中的状态
        User user = (User) session.getAttribute("user");
        Integer id = user.getId();
        String username = user.getUsername();
//        approval.setUid(id);
        // 多种角色，最好每一个人有一种角色
        List<Integer> role = roleService.queryUserRoleById(id);
        Integer integer = role.get(0);
        Role byId = roleService.getById(integer);
        String roleName = byId.getName();

        if (StringUtils.equals(roleName,"学生")){
            dataView.setCode(100);
            dataView.setMsg(roleName+"角色不能进行审批！");
            return dataView;
        }else if (StringUtils.equals(roleName,"管理员")){
            dataView.setCode(100);
            dataView.setMsg(roleName+"角色不能进行审批！");
            return dataView;
        }
        // 2.查询节点状态
        Approval serviceById = approvalService.getById(approval.getId());
        Integer nodeStatus = serviceById.getNodeStatus();
        // 如果时审批中状态，才可以进行审批同意
        if ( (StringUtils.equals(String.valueOf(ApprovalNodeStatusEnum.TEACHER_ING.getCode()),String.valueOf(nodeStatus)))
            || (StringUtils.equals(String.valueOf(ApprovalNodeStatusEnum.COLLEGE_ING.getCode()),String.valueOf(nodeStatus)))
        ){
            if (StringUtils.equals(roleName,"教师")){
                if ((StringUtils.equals(String.valueOf(ApprovalNodeStatusEnum.TEACHER_ING.getCode()),String.valueOf(nodeStatus)))){
                approval.setNodeStatus(ApprovalNodeStatusEnum.COLLEGE_ING.getCode());
                }
                else {
                    dataView.setCode(100);
                    dataView.setMsg(roleName+"不能越级审批！");
                    return dataView;
                }
            }
            else if (StringUtils.equals(roleName,"院系")){
                if ((StringUtils.equals(String.valueOf(ApprovalNodeStatusEnum.COLLEGE_ING.getCode()),String.valueOf(nodeStatus)))){
                    approval.setNodeStatus(ApprovalNodeStatusEnum.COLLEGE_PASSED.getCode());
                }
                else {
                    dataView.setCode(100);
                    dataView.setMsg("请等待老师审批！");
                    return dataView;
                }
            }
            else {
                dataView.setCode(100);
                dataView.setMsg(roleName+"角色不能审批！");
                return dataView;
            }

            // 修改库
            approvalService.updateById(approval);
            dataView.setCode(200);
            dataView.setMsg(username+"：角色："+roleName+"审批成功！");
            return dataView;
        }

        dataView.setCode(100);
        dataView.setMsg("此状态不能够去审批！");
        return dataView;
    }


    @RequestMapping("/rejectApproval")
    @ResponseBody
    public DataView rejectApproval(Approval approval,HttpSession session){
        DataView dataView = new DataView();
        approval.setUpdateTime(new Date());
        // 1.首先判断是不是数据库中 审核中的状态
        User user = (User) session.getAttribute("user");
        Integer id = user.getId();
        String username = user.getUsername();
//        approval.setUid(id);
        // 多种角色，最好每一个人有一种角色
        List<Integer> role = roleService.queryUserRoleById(id);
        Integer integer = role.get(0);
        Role byId = roleService.getById(integer);
        String roleName = byId.getName();
        if (StringUtils.equals(roleName,"学生")){
            dataView.setCode(100);
            dataView.setMsg(roleName+"角色不能进行审批！");
            return dataView;
        }else if (StringUtils.equals(roleName,"管理员")){
            dataView.setCode(100);
            dataView.setMsg(roleName+"角色不能进行审批！");
            return dataView;
        }

        // 2.查询节点状态
        Approval serviceById = approvalService.getById(approval.getId());
        Integer nodeStatus = serviceById.getNodeStatus();
        // 如果时审批中状态，才可以进行审批同意
        if ( (StringUtils.equals(String.valueOf(ApprovalNodeStatusEnum.TEACHER_ING.getCode()),String.valueOf(nodeStatus)))
                || (StringUtils.equals(String.valueOf(ApprovalNodeStatusEnum.COLLEGE_ING.getCode()),String.valueOf(nodeStatus)))
        ){
            if (StringUtils.equals(roleName,"教师")){
                if ((StringUtils.equals(String.valueOf(ApprovalNodeStatusEnum.TEACHER_ING.getCode()),String.valueOf(nodeStatus)))){
                    approval.setNodeStatus(ApprovalNodeStatusEnum.TEACHER_REJECTED.getCode());
                }
                else {
                    dataView.setCode(100);
                    dataView.setMsg(roleName+"不能越级审批！");
                    return dataView;
                }

            }else if (StringUtils.equals(roleName,"院系")){
                if ((StringUtils.equals(String.valueOf(ApprovalNodeStatusEnum.COLLEGE_ING.getCode()),String.valueOf(nodeStatus)))){
                    approval.setNodeStatus(ApprovalNodeStatusEnum.COLLEGE_REJECTED.getCode());
                }
                else {
                    dataView.setCode(100);
                    dataView.setMsg("请等待老师审批！");
                    return dataView;
                }

            }else {
                dataView.setCode(100);
                dataView.setMsg(roleName+"角色不能审批！");
                return dataView;
            }

            // 修改库
            approvalService.updateById(approval);
            dataView.setCode(200);
            dataView.setMsg(username+"：角色："+roleName+"驳回成功！");
            return dataView;
        }

        dataView.setCode(100);
        dataView.setMsg("此状态不能够去驳回！");
        return dataView;
    }
}
